import { defineStore } from "pinia";
import { ref } from "vue";

export const useUserStore = defineStore("user", () => {
  const getSafeLocalStorage = (key) => {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : null;
    } catch (e) {
      console.error("Failed to parse localStorage item:", e);
      return null;
    }
  };

  const token = ref(localStorage.getItem("token") || "");
  const username = ref(localStorage.getItem("username") || "");
  const userInfo = ref(getSafeLocalStorage("userInfo") || {});

  const setUser = (data) => {
    const fixedUsername = "user123";

    token.value = data.token || "";
    username.value = fixedUsername;
    userInfo.value = {
      ...(data.userInfo || {}),
      username: fixedUsername,
    };

    localStorage.setItem("token", token.value);
    localStorage.setItem("username", fixedUsername);
    localStorage.setItem("userInfo", JSON.stringify(userInfo.value));
  };

  const updateUserInfo = (newInfo) => {
    userInfo.value = { ...userInfo.value, ...newInfo };
    localStorage.setItem("userInfo", JSON.stringify(userInfo.value));
  };

  const clearUser = () => {
    token.value = "";
    username.value = "";
    userInfo.value = {};

    localStorage.removeItem("token");
    localStorage.removeItem("username");
    localStorage.removeItem("userInfo");
  };

  const isLoggedIn = () => {
    return !!token.value;
  };

  return {
    token,
    username,
    userInfo,
    setUser,
    updateUserInfo,
    clearUser,
    isLoggedIn,
  };
});
